// pages/ticket/ticket.js
import request from "../../utils/request.js";
import themeManager from "../../utils/theme.js";

Page(themeManager.enhancePage({
  data: {
    ticket: {},
    currentTheme: 'dark',
    chatHistory: [],
    loading: false,
    inputMessage: '',
    scrollTop: 0,
    scrollIntoView: ''
  },

  onLoad: function (options) {
    // 获取从上一页传递的参数
    this.loadTicketData(options.ticketId)
  },  // 加载工单数据
  loadTicketData: function (ticketId) {
    this.setData({ loading: true });
    
    console.log('加载工单数据:', ticketId)
    request
      .get("/tickets/my_tickets/" + ticketId)
      .then((res) => {
        if (res && res.data) {
          // 处理聊天记录数据
          console.log('原始聊天记录:', res.data.chat_history); // 添加调试信息
          const chatHistory = this.processChatHistory(res.data.chat_history || []);
          
          this.setData({
            ticket: res.data,
            chatHistory: chatHistory,
            loading: false
          });
          
          // 滚动到最新消息
          this.scrollToBottom();
        }
      })
      .catch((err) => {
        console.error("加载工单详情失败:", err);
        this.showError("加载工单详情失败，请稍后重试");
        this.setData({ loading: false });
      });
  },

  // 格式化时间
  formatTime: function(timeStr) {
    const date = new Date(timeStr);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    
    const timeFormat = date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
    
    if (messageDate.getTime() === today.getTime()) {
      return `今天 ${timeFormat}`;
    } else if (messageDate.getTime() === today.getTime() - 24 * 60 * 60 * 1000) {
      return `昨天 ${timeFormat}`;
    } else {
      return date.toLocaleDateString('zh-CN') + ' ' + timeFormat;
    }
  },

  // 滚动到底部
  scrollToBottom: function() {
    const chatHistory = this.data.chatHistory;
    if (chatHistory.length > 0) {
      const lastMessageId = `msg-${chatHistory[chatHistory.length - 1].id}`;
      this.setData({
        scrollIntoView: lastMessageId
      });
    }
  },

  // 消息输入
  onMessageInput: function(e) {
    this.setData({
      inputMessage: e.detail.value
    });
  },

  // 处理聊天记录数据
  processChatHistory: function(chatHistory) {
    if (!Array.isArray(chatHistory)) return [];
    
    // 先按原始时间排序，再格式化
    return chatHistory
      .slice()
      .sort((a, b) => new Date(a.created_at) - new Date(b.created_at))
      .map((item, index) => ({
        id: item.uuid,
        content: item.content,
        created_at: this.formatTime(item.created_at),
        type: item.type, // 0: 用户消息，1: 管理员消息
        sender_name: item.type === 0 ? '' : item.subject
      }));
  },

  // 发送消息
  sendMessage: function() {
    const message = this.data.inputMessage.trim();
    if (!message) return;
    
    const ticketId = this.data.ticket.uuid;
    if (!ticketId) {
      wx.showToast({
        title: '工单信息异常',
        icon: 'error'
      });
      return;
    }
    
    // 显示发送中状态
    wx.showLoading({
      title: '发送中...'
    });
    
    // 调用API发送消息
    request.post(`/tickets/${ticketId}/supply`, {content: message})
    .then(res => {
      wx.hideLoading();
      if (res) {
        // 清空输入框
        this.setData({
          inputMessage: ''
        });
        
        // 重新加载聊天记录
        this.loadTicketData(ticketId);
        
        wx.showToast({
          title: '发送成功',
          icon: 'success'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('发送消息失败:', err);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'error'
      });
    });
  },

  closeTicket: function() {
    wx.showModal({
      title: '提示',
      content: '结单操作不可撤销，请确认问题解决后再进行结单操作！',
      confirmText: '确定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          const ticketId = this.data.ticket.uuid;
          if (!ticketId) {
            this.showError('工单信息异常');
            return;
          }
          request.post(`/tickets/${ticketId}/close`)
            .then(() => {
              wx.showToast({
                title: '结单成功',
                icon: 'success'
              });

              this.setData({
                'ticket.status': 3 // 更新工单状态为已结单
              });
              
              setTimeout(() => {
                wx.navigateBack();
              }, 1000);
            })
            .catch((err) => {
              wx.hideLoading();
              console.error('结单失败:', err);
              this.showError('结单失败，请稍后重试');
            });
        }
      }
    });
  },

  
  // 显示错误信息
  showError: function(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  }
}))
